package com.niji.littly_donkey_android.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.activity.GetPhoneCodeActivity;
import com.niji.littly_donkey_android.activity.HomePageActivity;
import com.niji.littly_donkey_android.activity.IndexActivity;
import com.niji.littly_donkey_android.activity.ScreenDetailsActivity;
import com.niji.littly_donkey_android.bean.Comment;
import com.niji.littly_donkey_android.bean.Video;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.listener.MultiTouchListener;
import com.niji.littly_donkey_android.util.*;
import com.niji.littly_donkey_android.view.CircleImageView;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyViewPagerAdapter extends PagerAdapter {
    private static final String TAG = "MyViewPagerAdapter";

    Context context;
    private int commentNumber ;
    Activity activity ;
    //主线程传来的数据 每一个videoBean 是一个数据集
    private List<Video> videoBeans;
    //存放viewpage视频信息
    private Map<Integer, VideoView> mapVideo = new HashMap<>();
    //存放viewpage视频信息
    private Map<Integer, CircleImageView> musicCircle = new HashMap<>();
    //存放viewpage视频信息
    private Map<Integer, TextView> commentNumText = new HashMap<>();
    //当前的view
    private View mCurrentView;
    //视频在哪
    int point;

    private static ArrayList<Comment> parentComment ;

    private static ArrayList<Comment> childComments ;

    public MyViewPagerAdapter(){
    }

    public MyViewPagerAdapter(Context context,List<Video> videoBeans){
            this.context = context;
            this.videoBeans = videoBeans;
            activity = (Activity)context;
    }

    @Override
    public int getCount() {
        //页卡的数量
        return videoBeans.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }


    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        System.out.println(position+"---------------"+container.getChildCount()+"-----"+videoBeans.size());
        
        View view = View.inflate(this.context, R.layout.item_video_per, null);
        final VideoView currentVideoView = view.findViewById(R.id.videoView);
        final TextView item_index_video_id = view.findViewById(R.id.item_index_video_id);
        final CircleImageView item_index_music = view.findViewById(R.id.item_index_music);
        final CircleImageView item_img_head = view.findViewById(R.id.item_img_head);
        final Button item_img_share = view.findViewById(R.id.item_img_share);
        final Button item_img_comment = view.findViewById(R.id.item_img_comment);
        final Button item_img_heart = view.findViewById(R.id.item_img_heart);
        final Button item_index_want_go = view.findViewById(R.id.item_index_want_go);
        final EditText item_index_comment = view.findViewById(R.id.item_index_comment);
        final TextView item_text_shareNum = view.findViewById(R.id.item_text_shareNum);
        final TextView item_text_commentNum = view.findViewById(R.id.item_text_commentNum);
        final TextView item_text_commission = view.findViewById(R.id.item_text_commission);
        final TextView item_text_introduce = view.findViewById(R.id.item_text_introduce);
        final TextView item_text_name = view.findViewById(R.id.item_text_name);
        final TextView item_text_heartNum = view.findViewById(R.id.item_text_heartNum);
        final ImageView item_text_commission_logo = view.findViewById(R.id.item_text_commission_logo);
        final ImageView item_index_video_cover = view.findViewById(R.id.item_index_video_cover);
        final RelativeLayout item_video_play = view.findViewById(R.id.item_video_play);
        item_text_name.setText("@" + videoBeans.get(position).getNickname());
        NetworkGlideImageLoader.getInstance().displayImage((Activity) this.context,videoBeans.get(position).getAvatar(),item_img_head,0,0);
        NetworkGlideImageLoader.getInstance().displayImage((Activity) this.context,(UrlUtil.URL + videoBeans.get(position).getCover()),item_index_video_cover,0,0);
        NetworkGlideImageLoader.getInstance().displayImage((Activity) this.context,videoBeans.get(position).getAvatar(),item_index_music,0,0);
        if (videoBeans.get(position).isIs_likes()){
            item_img_heart.setBackground(view.getResources().getDrawable(R.mipmap.smallheart));
        }else {
            item_img_heart.setBackground(view.getResources().getDrawable(R.mipmap.praisetoicon));
        }
        commentNumber = videoBeans.get(position).getComments();
        item_index_video_id.setText("" + videoBeans.get(position).getId());
        item_text_introduce.setText(videoBeans.get(position).getTitle());
        item_text_heartNum.setText("" + videoBeans.get(position).getLikes());
        item_text_commentNum.setText("" + videoBeans.get(position).getComments());
        item_text_shareNum.setText("" + videoBeans.get(position).getShares());


        if (videoBeans.get(position).getCommission() == 1){
            item_text_commission.setVisibility(View.INVISIBLE);
            item_text_commission_logo.setVisibility(View.INVISIBLE);
            item_index_want_go.setText("发表评论");
        }else if(videoBeans.get(position).getCommission() == 2){
            item_text_commission.setVisibility(View.VISIBLE);
            item_text_commission_logo.setVisibility(View.VISIBLE);
            item_index_want_go.setText("想去这里");
        }
        VideoView beforeVideo = null;
        currentVideoView.setVideoPath(videoBeans.get(position).getUrl());
        currentVideoView.setKeepScreenOn(true);
        currentVideoView.requestFocus();
        currentVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });

        //设置缩率图
        BitmapDrawable imageBitmap = new BitMapUtils().getImageBitmap(UrlUtil.URL + videoBeans.get(position).getCover());
      //  System.out.println( null == imageBitmap ? "111" : "222"); 判断bitmap是否为空
        currentVideoView.setBackground(imageBitmap);
        currentVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                currentVideoView.setBackground(null);
            }
        });

       //分享
        item_img_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent( Intent.ACTION_SEND);
                intent.setType( "text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, videoBeans.get(position).getUrl());
                container.getContext().startActivity(Intent.createChooser(intent, "分享视频地址到..."));
            }
        });

        //点击头像

        item_img_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyViewPagerAdapter.this.context, HomePageActivity.class);
                intent.putExtra("user_id","" + videoBeans.get(position).getUserId());
                intent.putExtra("is_attention",videoBeans.get(position).isIs_attention());
                container.getContext().startActivity(intent);
            }
        });

        //点赞
        item_img_heart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(videoBeans != null ){
                    if(videoBeans.size() == 0){
                        Toast.makeText(MyViewPagerAdapter.this.context,"未获取视频",Toast.LENGTH_SHORT).show();
                    }else {
                        if(item_img_heart.getBackground().getConstantState().equals(MyViewPagerAdapter.this.context.getResources().getDrawable(R.mipmap.praisetoicon).getConstantState())){
                            Integer id = (Integer) videoBeans.get(position).getId();
                            String url = UrlUtil.URL + "/user/give/likes";
                            RequestQueue requestQueue= Volley.newRequestQueue(MyViewPagerAdapter.this.context);
                            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                    try {
                                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                                        Integer code = (Integer) map.get("code");
                                        if (code == 0) {
                                            Toast.makeText(MyViewPagerAdapter.this.context, "点赞成功", Toast.LENGTH_LONG).show();
                                            String trim = item_text_heartNum.getText().toString().trim();
                                            item_text_heartNum.setText("" + (Integer.parseInt(trim) + 1));
                                            item_img_heart.setBackground(MyViewPagerAdapter.this.context.getResources().getDrawable(R.mipmap.smallheart));
                                        } else if(code == -1){
                                            Toast.makeText(MyViewPagerAdapter.this.context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                            Intent intent = new Intent(MyViewPagerAdapter.this.context, GetPhoneCodeActivity.class);
                                            intent.putExtra("loginCode","-1");
                                            container.getContext().startActivity(intent);
                                            activity.finish();
                                        }else {
                                            Object message = map.get("message");
                                            Toast.makeText(MyViewPagerAdapter.this.context, message.toString(), Toast.LENGTH_SHORT).show();
                                            activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                            activity.finish();
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e(TAG, volleyError.getMessage(), volleyError);
                                }
                            }) {
                                @Override
                                protected Map<String, String> getParams() throws AuthFailureError {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("videos_id",String.valueOf(id));
                                    return map;
                                }

                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    String sesseionid = new ConnectViaSession(context).GetSession();
                                    if (!sesseionid.equals("")) {
                                        HashMap<String, String> headers = new HashMap<String, String>();
                                        headers.put("cookie", sesseionid);
                                        return headers;
                                    } else {
                                        return super.getHeaders();
                                    }
                                }
                            };

                            requestQueue.add(stringRequest);
                        }else {
                            Integer id = (Integer) videoBeans.get(position).getId();
                            String url = UrlUtil.URL + "/user/cancel/give/likes?videos_id=" + id;
                            RequestQueue requestQueue= Volley.newRequestQueue(MyViewPagerAdapter.this.context);
                            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                    try {
                                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                                        Integer code = (Integer) map.get("code");
                                        if (code == 0) {
                                            Toast.makeText(MyViewPagerAdapter.this.context, "取消点赞成功", Toast.LENGTH_LONG).show();
                                            String trim = item_text_heartNum.getText().toString().trim();
                                            item_text_heartNum.setText("" + (Integer.parseInt(trim) - 1));
                                            item_img_heart.setBackground(MyViewPagerAdapter.this.context.getResources().getDrawable(R.mipmap.praisetoicon));
                                        } else if(code == -1){
                                            Toast.makeText(MyViewPagerAdapter.this.context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                            Intent intent = new Intent(MyViewPagerAdapter.this.context, GetPhoneCodeActivity.class);
                                            intent.putExtra("loginCode","-1");
                                            container.getContext().startActivity(intent);
                                            activity.finish();
                                        }else {
                                            Object message = map.get("message");
                                            Toast.makeText(MyViewPagerAdapter.this.context, message.toString(), Toast.LENGTH_SHORT).show();
                                            activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                            activity.finish();
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e(TAG, volleyError.getMessage(), volleyError);
                                }
                            }) {

                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    String sesseionid = new ConnectViaSession(context).GetSession();
                                    if (!sesseionid.equals("")) {
                                        HashMap<String, String> headers = new HashMap<String, String>();
                                        headers.put("cookie", sesseionid);
                                        return headers;
                                    } else {
                                        return super.getHeaders();
                                    }
                                }
                            };

                            requestQueue.add(stringRequest);
                        }
                    }
                }
            }
//            }
        });
        
        //显示评论
        item_img_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(videoBeans.get(position).getId() != -1){
                   getParentComment(v);
                }


            }
        });
        //发表评论
        item_index_comment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                item_index_want_go.setText("发表评论");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!"".equals(s.toString())){
                    item_index_want_go.setText("发表评论");
                }else {
                    if (videoBeans.get(position).getCommission() == 2){
                        item_index_want_go.setText("想去这里");
                    }
                }

            }
        });


        /**
         * 发表评论或购票
         */
        item_index_want_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String want_go_name = item_index_want_go.getText().toString().trim();
                if(want_go_name.equals("发表评论")){
                    String commenContent = item_index_comment.getText().toString().trim();
                    if(!commenContent.equals("")){
                        sendComment();
                    }else {
                        Toast.makeText(context,"请输入评论内容",Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Intent intent = new Intent(context, ScreenDetailsActivity.class);
//                    intent.putExtra("attractions_id",attractions_id);
                    intent.putExtra("attractions_id",String.valueOf(videoBeans.get(position).getAttractionsId()));
                    activity.startActivity(intent);
                }
            }
        });


//       currentVideoView.setOnTouchListener(new MultiTouchListener() {
//           @Override
//           public boolean onMultiTouch(View v, MotionEvent event, int touchCount) {
//               switch (touchCount){
//                   case 1:
//                       if(currentVideoView.isPlaying()){
//                           item_video_play.setVisibility(View.VISIBLE);
//                           currentVideoView.pause();
//                       }else {
//                           item_video_play.setVisibility(View.INVISIBLE);
//                           currentVideoView.start();
//                       }
//                       break;
//                   default:
//                       System.out.println(touchCount);
//                       if(item_img_heart.getBackground().getConstantState().equals(MyViewPagerAdapter.this.context.getResources().getDrawable(R.mipmap.praisetoicon).getConstantState())){
//                           Integer id = (Integer) videoBeans.get(position).getId();
//                           String url = UrlUtil.URL + "/user/give/likes";
//                           RequestQueue requestQueue= Volley.newRequestQueue(MyViewPagerAdapter.this.context);
//                           StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//                               @Override
//                               public void onResponse(String s) {
//                                   try {
//                                       Map<String, Object> map = JsonUtil.jsonToMap(s);
//                                       Integer code = (Integer) map.get("code");
//                                       if (code == 0) {
//                                           Toast.makeText(MyViewPagerAdapter.this.context, "点赞成功", Toast.LENGTH_LONG).show();
//                                           String trim = item_text_heartNum.getText().toString().trim();
//                                           item_text_heartNum.setText("" + (Integer.parseInt(trim) + 1));
//                                           item_img_heart.setBackground(MyViewPagerAdapter.this.context.getResources().getDrawable(R.mipmap.smallheart));
//                                       } else if(code == -1){
//                                           Toast.makeText(MyViewPagerAdapter.this.context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
//                                           Intent intent = new Intent(MyViewPagerAdapter.this.context, GetPhoneCodeActivity.class);
//                                           intent.putExtra("loginCode","-1");
//                                           container.getContext().startActivity(intent);
//                                           activity.finish();
//                                       }else {
//                                           Object message = map.get("message");
//                                           Toast.makeText(MyViewPagerAdapter.this.context, message.toString(), Toast.LENGTH_SHORT).show();
//                                           activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
//                                           activity.finish();
//                                       }
//
//                                   } catch (JSONException e) {
//                                       e.printStackTrace();
//                                   } catch (Exception e) {
//                                       e.printStackTrace();
//                                   }
//                               }
//                           }, new Response.ErrorListener() {
//                               @Override
//                               public void onErrorResponse(VolleyError volleyError) {
//                                   Log.e(TAG, volleyError.getMessage(), volleyError);
//                               }
//                           }) {
//                               @Override
//                               protected Map<String, String> getParams() throws AuthFailureError {
//                                   Map<String, String> map = new HashMap<>();
//                                   map.put("videos_id",String.valueOf(id));
//                                   return map;
//                               }
//
//                               @Override
//                               public Map<String, String> getHeaders() throws AuthFailureError {
//                                   String sesseionid = new ConnectViaSession(context).GetSession();
//                                   if (!sesseionid.equals("")) {
//                                       HashMap<String, String> headers = new HashMap<String, String>();
//                                       headers.put("cookie", sesseionid);
//                                       return headers;
//                                   } else {
//                                       return super.getHeaders();
//                                   }
//                               }
//                           };
//
//                           requestQueue.add(stringRequest);
//                       }
//                       break;
//               }
//               return true;
//           }
//       });

        currentVideoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:// 按下去时，记录按下的坐标和时间，用于判断是否是点击事件
                        downX = (int) event.getX();
                        downTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:// 抬起手指时，判断落下抬起的时间差和坐标，符合以下条件为点击
                        // Toast.makeText(context, "手指抬起了", 0).show();
                        if (System.currentTimeMillis() - downTime < 500
                                && Math.abs(downX - event.getX()) < 30) {// ★考虑到手按下和抬起时的坐标不可能完全重合，这里给出30的坐标偏差
                            // 点击事件被触发
                            if(currentVideoView.isPlaying()){
                                item_video_play.setVisibility(View.VISIBLE);
                                currentVideoView.pause();
                            }else {
                                item_video_play.setVisibility(View.INVISIBLE);
                                currentVideoView.start();
                            }
                        }
                        break;

                }
                return true;
            }
        });


        mapVideo.put(position,currentVideoView);
        musicCircle.put(position,item_index_music);
        commentNumText.put(position,item_text_commentNum);
        container.addView(view);
        return view;
    }

   private long downTime = System.currentTimeMillis();
    private int downX = 0;


    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }


    @Override
    public void restoreState(@Nullable Parcelable state, @Nullable ClassLoader loader) {
    }

    @Nullable
    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void finishUpdate(@NonNull ViewGroup container) {
        System.out.println(mapVideo.size()+"mapvideosize");

        //准备开始时
        if(mapVideo.size()  == 2){
            mapVideo.get(0).start();
            mapVideo.get(1).pause();
        }else {
            mapVideo.get(mapVideo.size()-1).pause();
            mapVideo.get(mapVideo.size()-2).start();
            mapVideo.get(mapVideo.size()-3).pause();

        }

        if (point == mapVideo.size() - 1){
            ToastUitls.showLongToast(context,"已经到底部了");
        }
        if(point == 0){
            ToastUitls.showLongToast(context,"已经到顶部了");
        }
        //向上翻时
        if(!getCurrentVideoView(mCurrentView).isPlaying()){
            getCurrentVideoView(mCurrentView).start();

            //当前位置的viedoview正在播放时
            if(point >= 1) {
                if (mapVideo.get(point).isPlaying()) {
                    mapVideo.get(point+1).pause();
                    mapVideo.get(point-1).pause();
                }
            }else {
                mapVideo.get(point+1).pause();
            }
        }
        Animation animation = AnimationUtils.loadAnimation(container.getContext(), R.anim.img_range);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        animation.setInterpolator(linearInterpolator);
        musicCircle.get(point).startAnimation(animation);


    }

    @Override
    public void startUpdate(@NonNull ViewGroup container) {


    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        mCurrentView = (View)object;
        point = position;
        System.out.println(point+"这是point");
    }

    public VideoView getCurrentVideoView(View currentView){
        return currentView.findViewById(R.id.videoView);
    }

    private void getParentComment(View v){
        ArrayList<Comment> comments = new ArrayList<>();
        String url = UrlUtil.URL + "/user/comments/videos/list?vid=" + videoBeans.get(point).getId();
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Log.i(TAG,data.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) data.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Comment comment = new Comment();
                            Integer id1 = (Integer) mapList.get(i).get("id");
                            Integer user_id = (Integer) mapList.get(i).get("user_id");
                            Integer video_id = (Integer) mapList.get(i).get("video_id");
                            Integer parent = (Integer) mapList.get(i).get("parent");
                            String user_nickname = (String) mapList.get(i).get("user_nickname");
                            String user_avatar = (String) mapList.get(i).get("user_avatar");
                            String content = (String) mapList.get(i).get("content");
                            String  picture = (String) mapList.get(i).get("picture");
                            String  created_at = (String) mapList.get(i).get("created_at");
                            Integer likes = (Integer) mapList.get(i).get("likes");
                            Integer reply = (Integer) mapList.get(i).get("reply");
                            Boolean is_likes = (Boolean) mapList.get(i).get("is_likes");
                            comment.setTime(created_at);
                            comment.setId(id1);
                            comment.setTitle(user_nickname);
                            comment.setMessage(content);
                            comment.setLikes(likes);
                            comment.setReply(reply);
                            comment.setLike(is_likes);
                            comment.setHead(UrlUtil.URL + user_avatar);
                            getChildComment(id1);
                            comment.setComments(childComments);
                            comments.add(comment);

                        }
                        parentComment = comments;
                        showPopupWindow(v);

                    } else if(code == -1){
                        Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        activity.startActivity(intent);
                        activity.finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                        activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        activity.finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(context).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    private void getChildComment(int pid){
        ArrayList<Comment> comments = new ArrayList<>();
        String url = UrlUtil.URL + "/user/comments/videos/child?pid=" + pid;
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Log.i(TAG,data.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) data.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Comment comment = new Comment();
                            Integer id1 = (Integer) mapList.get(i).get("id");
                            Integer user_id = (Integer) mapList.get(i).get("user_id");
                            Integer video_id = (Integer) mapList.get(i).get("video_id");
                            Integer parent = (Integer) mapList.get(i).get("parent");
                            String user_nickname = (String) mapList.get(i).get("user_nickname");
                            String user_avatar = (String) mapList.get(i).get("user_avatar");
                            String content = (String) mapList.get(i).get("content");
                            String  picture = (String) mapList.get(i).get("picture");
                            String  created_at = (String) mapList.get(i).get("created_at");
                            Integer likes = (Integer) mapList.get(i).get("likes");
                            Integer reply = (Integer) mapList.get(i).get("reply");
                            Boolean is_likes = (Boolean) mapList.get(i).get("is_likes");
                            comment.setTime(created_at);
                            comment.setId(id1);
                            comment.setTitle(user_nickname);
                            comment.setLikes(likes);
                            comment.setReply(reply);
                            comment.setMessage(content);
                            comment.setLike(is_likes);
                            comment.setHead(UrlUtil.URL  + user_avatar);
                            comments.add(comment);

                        }
                        childComments = comments;

                    } else if(code == -1){
                        Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        activity.startActivity(intent);
                        activity.finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                        activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        activity.finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(context).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    /**
     * 显示
     *
     * @param targetView 需要显示的内容view
     * @return
     */
    public void showPopupWindow(View targetView) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.dialog_comment, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,  ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        Button cancel_comment = contentView.findViewById(R.id.cancel_comment);
        cancel_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
////                Log.i("mengdd", "onTouch : ");
//
//                return false;
//                // 这里如果返回true的话，touch事件将被拦截
//                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
//            }
//        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(context.getResources().getDrawable(
                R.drawable.shape_top_round_white));
        if(videoBeans.get(point).getId() != -1){
            if(parentComment == null){
                RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                no_comment.setVisibility(View.VISIBLE);
            }else {
                if(parentComment.size() == 0){
                    RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                    no_comment.setVisibility(View.VISIBLE);
                }else {
                    RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
                    no_comment.setVisibility(View.GONE);
                    TextView index_comment_commentNum = contentView.findViewById(R.id.index_comment_commentNum);
                    ListView index_comment_listview = contentView.findViewById(R.id.index_comment_listview);
                    index_comment_commentNum.setText("" + parentComment.size() + "条评论");
                    index_comment_listview = contentView.findViewById(R.id.index_comment_listview);
                    IndexCommentAdapter indexCommentAdapter = new IndexCommentAdapter(context, parentComment);
                    index_comment_listview.setAdapter(indexCommentAdapter);
                }
            }

        }else {
            RelativeLayout no_comment = contentView.findViewById(R.id.no_comment);
            no_comment.setVisibility(View.VISIBLE);
        }
        // 设置好参数之后再show
        int[] location = new int[2];
        targetView.getLocationOnScreen(location);
        popupWindow.showAtLocation(targetView, Gravity.LEFT|Gravity.BOTTOM,0,-location[1]);


    }

    /**
     * 发送评论
     */
    private void sendComment() {
        EditText index_comment = mCurrentView.findViewById(R.id.item_index_comment);
        String commentContent = index_comment.getText().toString().trim();
        if(!commentContent.equals("")){
            String url = UrlUtil.URL + "/user/comments/add";
            RequestQueue requestQueue= Volley.newRequestQueue(context);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        Map<String, Object> map = JsonUtil.jsonToMap(s);
                        Integer code = (Integer) map.get("code");
                        if (code == 0) {
                            Toast.makeText(context, "评论发表成功", Toast.LENGTH_LONG).show();
                            index_comment.setText("");
                            commentNumber = Integer.parseInt(commentNumText.get(point).getText().toString().trim())  + 1 ;
                            commentNumText.get(point).setText("" + commentNumber);
                            getParentComment(mCurrentView);
                        } else if(code == -1){
                            Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                            intent.putExtra("loginCode","-1");
                            activity.startActivity(intent);
                            activity.finish();
                        }else {
                            Object message = map.get("message");
                            Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                            activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            activity.finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.e(TAG, volleyError.getMessage(), volleyError);
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("video_id",String.valueOf(videoBeans.get(point).getId()));
                    map.put("content",commentContent);
                    return map;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    String sesseionid = new ConnectViaSession(context).GetSession();
                    if (!sesseionid.equals("")) {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        headers.put("cookie", sesseionid);
                        return headers;
                    } else {
                        return super.getHeaders();
                    }
                }
            };

            requestQueue.add(stringRequest);
        }
    }


}
